import React, { useEffect, useState } from 'react';
import { Table, Button, Space, Input, message, Modal, Form, Select, Tag, Upload, DatePicker } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { listBookByPage, updateBook, deleteBook, getBookById, addBook } from '@/api/bookController';
import { listBookCategories } from '@/api/bookCategoryController';
import { LoadingOutlined, PlusOutlined, SearchOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd/es/upload';
import type { RcFile } from 'antd/es/upload/interface';
import dayjs from 'dayjs';
import { withAdminAuth } from '@/components/AdminAuth';

interface BookData {
  id: string;
  bookname: string;
  bookdesc: string;
  bookauthor: string;
  isbn: string;
  publisher: string;
  publishdate: string;
  price: number;
  stock: number;
  imageurl: string;
  categorycode: string;
}

interface CategoryData {
  id: string;
  categorycode: string;
  categorynamezh: string;
}

function BookManagement() {
  const [bookList, setBookList] = useState<BookData[]>([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(8);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [currentBook, setCurrentBook] = useState<BookData | null>(null);
  const [categories, setCategories] = useState<CategoryData[]>([]);
  const [uploadLoading, setUploadLoading] = useState(false);
  const [modalType, setModalType] = useState<'edit' | 'add'>('edit');
  const [searchForm] = Form.useForm();
  const [form] = Form.useForm();

  // 获取图书分类列表
  const fetchCategories = async () => {
    try {
      const res = await listBookCategories();
      if (res.code === 200) {
        setCategories(res.data.filter(cat => cat.categorycode !== 'all'));
      }
    } catch (error) {
      message.error('获取分类列表失败');
    }
  };

  // 获取图书列表
  const fetchBooks = async () => {
    setLoading(true);
    try {
      const values = await searchForm.validateFields()
        .catch(() => ({}));
      
      // 构造搜索参数
      const searchParams = {
        current,
        pageSize,
        bookname: values.bookname || '',
        bookauthor: values.bookauthor || '',
        categorycode: values.categorycode ? [values.categorycode] : ['all']  // 修改为数组格式
      };

      const res = await listBookByPage(searchParams);
      if (res.code === 200) {
        setBookList(res.data.records);
        setTotal(parseInt(res.data.total));
      }
    } catch (error) {
      message.error('获取图书列表失败');
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchBooks();
    fetchCategories();
  }, [current, pageSize]);

  // 处理新增
  const handleAdd = () => {
    setModalType('add');
    form.resetFields();
    setIsModalVisible(true);
  };

  // 处理编辑
  const handleEdit = async (record: BookData) => {
    setModalType('edit');
    setCurrentBook(record);
    const categories = JSON.parse(record.categorycode).filter((code: string) => code !== 'all');
    form.setFieldsValue({
      ...record,
      publishdate: dayjs(record.publishdate),
      categorycode: categories
    });
    setIsModalVisible(true);
  };

  // 处理删除
  const handleDelete = async (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这本书吗？',
      onOk: async () => {
        try {
          const res = await deleteBook({ id });
          if (res.code === 200) {
            message.success('删除成功');
            fetchBooks();
          }
        } catch (error) {
          message.error('删除失败');
        }
      }
    });
  };

  // 处理表单提交
  const handleSubmit = async (values: any) => {
    try {
      const submitData = {
        ...values,
        publishdate: values.publishdate.format('YYYY-MM-DD'),
        categorycode: values.categorycode
      };

      let res;
      if (modalType === 'edit') {
        res = await updateBook({
          ...submitData,
          id: currentBook?.id,
        });
      } else {
        res = await addBook(submitData);
      }

      if (res.code === 200) {
        message.success(modalType === 'edit' ? '更新成功' : '添加成功');
        setIsModalVisible(false);
        fetchBooks();
      }
    } catch (error) {
      message.error(modalType === 'edit' ? '更新失败' : '添加失败');
    }
  };

  // 图片上传相关
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传 JPG/PNG 格式的图片!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  const handleChange: UploadProps['onChange'] = (info) => {
    if (info.file.status === 'uploading') {
      setUploadLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      if (info.file.response.code === 200) {
        setUploadLoading(false);
        const imageUrl = info.file.response.data;
        form.setFieldsValue({ imageurl: imageUrl });
        message.success('图片上传成功！');
      } else {
        setUploadLoading(false);
        message.error(info.file.response.message || '图片上传失败！');
      }
    }
  };

  const columns: ColumnsType<BookData> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 60,
    },
    {
      title: '图片',
      key: 'image',
      width: 100,
      render: (_, record) => (
        <img
          src={record.imageurl}
          alt={record.bookname}
          width={60}
          height={90}
          style={{ objectFit: 'cover' }}
        />
      ),
    },
    {
      title: '书名',
      dataIndex: 'bookname',
      key: 'bookname',
      width: 180,
    },
    {
      title: '作者',
      dataIndex: 'bookauthor',
      key: 'bookauthor',
      width: 120,
    },
    {
      title: 'ISBN',
      dataIndex: 'isbn',
      key: 'isbn',
      width: 140,
    },
    {
      title: '分类',
      dataIndex: 'categorycode',
      key: 'categorycode',
      width: 200,
      render: (categorycode: string) => {
        const codes = JSON.parse(categorycode).filter((code: string) => code !== 'all');
        return (
          <>
            {codes.map((code: string) => {
              const category = categories.find(cat => cat.categorycode === code);
              return (
                <Tag color="blue" key={code}>
                  {category?.categorynamezh || code}
                </Tag>
              );
            })}
          </>
        );
      }
    },
    {
      title: '出版社',
      dataIndex: 'publisher',
      key: 'publisher',
      width: 150,
    },
    {
      title: '出版日期',
      dataIndex: 'publishdate',
      key: 'publishdate',
      width: 120,
      render: (date: string) => date?.split(' ')[0],
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      width: 80,
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
          <Button type="link" danger onClick={() => handleDelete(record.id)}>删除</Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="p-4">
      <div className="mb-4">
        <Form
          form={searchForm}
          layout="inline"
          onFinish={fetchBooks}
        >
          <Form.Item name="bookname">
            <Input 
              placeholder="图书名称" 
              onPressEnter={() => searchForm.submit()}
            />
          </Form.Item>
          <Form.Item name="bookauthor">
            <Input 
              placeholder="作者"
              onPressEnter={() => searchForm.submit()}
            />
          </Form.Item>
          <Form.Item name="categorycode">
            <Select
              placeholder="选择分类"
              allowClear
              style={{ width: 200 }}
              options={categories.map(cat => ({
                label: cat.categorynamezh,
                value: cat.categorycode
              }))}
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={handleAdd}>
              新增图书
            </Button>
          </Form.Item>
        </Form>
      </div>

      <Table 
        columns={columns} 
        dataSource={bookList}
        rowKey="id"
        loading={loading}
        pagination={{
          total,
          current,
          pageSize,
          onChange: (page, size) => {
            setCurrent(page);
            setPageSize(size);
          },
        }}
      />

      <Modal
        title={modalType === 'edit' ? '编辑图书' : '新增图书'}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={800}
      >
        <Form
          form={form}
          onFinish={handleSubmit}
          layout="vertical"
        >
          <div className="grid grid-cols-2 gap-4">
            <Form.Item name="bookname" label="书名" rules={[{ required: true }]}>
              <Input />
            </Form.Item>
            <Form.Item name="bookauthor" label="作者" rules={[{ required: true }]}>
              <Input />
            </Form.Item>
            <Form.Item name="isbn" label="ISBN" rules={[{ required: true }]}>
              <Input />
            </Form.Item>
            <Form.Item name="publisher" label="出版社" rules={[{ required: true }]}>
              <Input />
            </Form.Item>
            <Form.Item name="publishdate" label="出版日期" rules={[{ required: true }]}>
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item name="price" label="价格" rules={[{ required: true }]}>
              <Input type="number" step="0.01" />
            </Form.Item>
            <Form.Item name="stock" label="库存" rules={[{ required: true }]}>
              <Input type="number" />
            </Form.Item>
            <Form.Item name="categorycode" label="分类" rules={[{ required: true }]}>
              <Select
                mode="multiple"
                placeholder="请选择分类"
                options={categories.map(cat => ({
                  label: cat.categorynamezh,
                  value: cat.categorycode
                }))}
              />
            </Form.Item>
          </div>

          <Form.Item name="bookdesc" label="图书描述">
            <Input.TextArea rows={4} />
          </Form.Item>

          <Form.Item label="图书封面" required>
            <Upload
              name="file"
              listType="picture-card"
              showUploadList={false}
              action="http://localhost:8081/api/file/upload"
              beforeUpload={beforeUpload}
              onChange={handleChange}
              data={{ biz: 'book_cover' }}
              withCredentials={true}
            >
              {form.getFieldValue('imageurl') ? (
                <img 
                  src={form.getFieldValue('imageurl')} 
                  alt="cover" 
                  style={{ width: '100%', height: '100%', objectFit: 'cover' }} 
                />
              ) : (
                <div>
                  {uploadLoading ? <LoadingOutlined /> : <PlusOutlined />}
                  <div style={{ marginTop: 8 }}>上传封面</div>
                </div>
              )}
            </Upload>
            <Form.Item name="imageurl" hidden>
              <Input />
            </Form.Item>
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
              <Button onClick={() => setIsModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default withAdminAuth(BookManagement); 